﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace d39
{
    public partial class GridBuild : GridPage
    {
        public override string SubTitle
        {
            get { return "Build"; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            Walls.SetEditableListDataSource(CurrentGrid.WallTypes, AddWallBtn,
                rebind,
                () => GridChanged(false, true));

            Terrains.SetEditableListDataSource(CurrentGrid.TerrainTypes, AddTerrainBtn,
                rebind,
                () => GridChanged(false, true));
        }

        private void rebind()
        {
            ActionUpdatePanel.Update();
            DataBind();
        }

        protected void ShowColorDiv_Click(object sender, EventArgs e)
        {
            GridColorDiv.Visible = true;
            rebind();
        }
        protected void ChangeColors_Click(object sender, EventArgs e)
        {
            CurrentGrid.Name = string.IsNullOrWhiteSpace(Name.Text.Trim()) ? null : Name.Text.Trim();
            CurrentGrid.BackgroundColor = BackgroundColor.Color;
            CurrentGrid.GridLineColor = GridLineColor.Color;
            GridColorDiv.Visible = false;
            GridChanged(false, true);
        }
        protected void CancelColors_Click(object sender, EventArgs e)
        {
            GridColorDiv.Visible = false;
            rebind();
        }

        public bool IsEditing { get { return Walls.EditIndex >= 0 || Terrains.EditIndex >= 0 || GridColorDiv.Visible; } }

        private void adjustSize(int addN, int addE, int addS, int addW)
        {
            CurrentGrid.Height += addN + addS;
            CurrentGrid.Width += addE + addW;
            bool shift = addW != 0 || addN != 0;
            if (shift) CurrentGrid.ShiftAllCoordinates(Vector.S * addN + Vector.E * addW);
            GridChanged(shift, true);
        }

        protected override void UpdateFromGrid(bool playersOrMovesChanged, bool wallTerrainChanged)
        {
            if (wallTerrainChanged) rebind();
        }

        protected void AdjustCommand(object sender, CommandEventArgs e)
        {
            int count = int.Parse("" + e.CommandArgument);
            switch (e.CommandName)
            {
                case "N":
                    adjustSize(count, 0, 0, 0);
                    break;
                case "E":
                    adjustSize(0, count, 0, 0);
                    break;
                case "S":
                    adjustSize(0, 0, count, 0);
                    break;
                case "W":
                    adjustSize(0, 0, 0, count);
                    break;
                default: throw new ArgumentException();
            }
        }
    }
}